<template>
  <div class="user-profile">
    <NavBar title="个人信息"></NavBar>
    <van-cell-group inset>
      <van-cell title="昵称" is-link @click="editName">
        <span slot="default">{{ profile.username }}</span>
      </van-cell>
      <van-cell title="头像" is-link center @click="$refs.fileRef.click()">
        <div slot="default">
          <van-image
            round
            fit="cover"
            width="35px"
            height="35px"
            :src="profile.decorate_avatar"
            lazy-load
          />
        </div>
      </van-cell>
      <van-cell
        title="简介"
        :value="profile.desc ? profile.desc : '编写您的简介'"
        is-link
        @click="editDesc"
      />
      <van-cell title="性别" :value="sex" is-link @click="sexChoose = true" />
      <van-cell
        title="生日"
        :value="currentDateStr"
        is-link
        @click="showBirthSheet = true"
      />
    </van-cell-group>
    <van-popup
      v-model="editing"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <div v-if="editNum == 0">
        <van-nav-bar
          title="编辑昵称"
          left-arrow
          right-text="提交"
          @click-left="closePopup"
          @click-right="updateName"
        />
        <van-cell>
          <van-field
            v-model="name"
            rows="1"
            autosize
            type="textarea"
            maxlength="10"
            :placeholder="profile.username"
            show-word-limit
            ref="nameIpt"
            @input="veriftyUserName"
            :error-message="usernameCount == 0 ? '' : '用户名已存在'"
          />
        </van-cell>
      </div>
      <div v-else-if="editNum == 1">
        <van-nav-bar
          title="编辑简介"
          left-arrow
          right-text="提交"
          @click-left="closePopup"
          @click-right="updateDesc"
        />
        <van-field
          v-model="desc"
          rows="2"
          autosize
          type="textarea"
          maxlength="500"
          :placeholder="profile.desc"
          ref="descIpt"
          show-word-limit
        />
      </div>
    </van-popup>
    <van-action-sheet
      v-model="sexChoose"
      :actions="actions"
      @select="onSelect"
      close-on-click-action
      close-on-popstate
      cancel-text="取消"
      round
    />
    <van-action-sheet
      v-model="showBirthSheet"
      @click-overlay="currentDate = maxDate"
    >
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择出生日期"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="
          showBirthSheet = false;
          currentDate = maxDate;
        "
        @confirm="updateBirthday"
      />
    </van-action-sheet>
    <input
      type="file"
      accept="image/*"
      @change="onFileChange"
      v-show="false"
      ref="fileRef"
    />
  </div>
</template>

<script>
import NavBar from "@/components/Home/NavBar";
import { mapState, mapActions, mapMutations } from "vuex";
import dayjs from "dayjs";
import {
  updateProfileAPI,
  loginAPI,
  uploadAvatarAPI,
  usernameCountAPI,
} from "@/api/userApi";
export default {
  data() {
    return {
      editing: false,
      editNum: 0,
      actions: [{ name: "男" }, { name: "女" }],
      name: "",
      desc: "",
      sexChoose: false,
      showBirthSheet: false,
      minDate: new Date(1900, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(),
      new_profile: {},
      usernameCount: 0,
    };
  },
  components: {
    NavBar,
  },
  computed: {
    ...mapState("user", ["profile", "tokenInfo"]),
    sex() {
      return this.actions[this.profile.sex].name;
    },
    currentDateStr() {
      return this.profile.birthday
        ? dayjs(new Date(this.profile.birthday)).format("YYYY-MM-DD")
        : dayjs(this.currentDate).format("YYYY-MM-DD");
    },
  },
  methods: {
    ...mapMutations("user", ["updateTokenInfo"]),
    ...mapActions("user", ["initProfile"]),
    editDesc() {
      this.editNum = 1;
      this.editing = true;
      this.$nextTick(() => {
        this.$refs.descIpt.focus();
      });
    },
    updateDesc() {
      this.new_profile.desc = this.desc;
      this.editing = false;
      this.desc = "";
      this.updateProfile();
    },
    editName() {
      this.editNum = 0;
      this.editing = true;
      this.$nextTick(() => {
        this.$refs.nameIpt.focus();
      });
    },
    updateName() {
      this.new_profile.username = this.name;
      this.editing = false;
      this.name = "";
      this.updateProfile(true);
    },
    async veriftyUserName(value) {
      if (!value) {
        return;
      }
      const { data: res } = await usernameCountAPI(value);
      if (res.message == "OK") {
        this.usernameCount = res.count;
      }
    },
    closePopup() {
      this.editing = false;
    },
    updateBirthday() {
      this.showBirthSheet = false;
      this.new_profile.birthday = dayjs(this.currentDate).format("YYYY-MM-DD");
      this.updateProfile();
    },
    onSelect(item) {
      this.new_profile.sex = this.actions.indexOf(item);
      this.updateProfile();
    },
    async onFileChange(e) {
      // 获取到用户选择的文件列表
      const files = e.currentTarget.files;
      // 如果没有选择任何文件，则不执行后续的业务逻辑
      if (files.length === 0) return;
      // 1.1 创建 FormData 的对象
      let fd = new FormData();
      // 1.2 向 fd 中追加数据项
      fd.append("photo", files[0]);
      fd.append("mobile", this.profile.mobile);
      const { data: res } = await uploadAvatarAPI(fd);
      if (res.message === "OK") {
        this.new_profile.avatar = res.avatar;
        this.updateProfile();
      }
    },
    async updateProfile(isChange = false) {
      try {
        const { data: res } = await updateProfileAPI(
          this.tokenInfo.user_id,
          this.new_profile
        );
        if (isChange) {
          const { data: reLogin } = await loginAPI(res.mobile, "", true);
          console.log("重新登录", reLogin);
          this.updateTokenInfo(reLogin.tokenInfo);
        }
        this.new_profile = {};
        if (res) {
          this.initProfile();
          this.$notify({
            type: "success",
            message: "修改成功",
            duration: 2000,
          });
        }
      } catch (e) {
        console.log(e);
      }
    },
  },
};
</script>

<style></style>
